package com.zwq.controller;

import com.zwq.pojo.dto.MachineDto;
import com.zwq.pojo.dto.MachineStatsDto;
import com.zwq.pojo.request.user.machine.MachineRequest;
import com.zwq.service.MachineService;
import com.zwq.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/machine")
public class MachineController {

    @Autowired
    private MachineService machineService;

    @GetMapping("/stats")
    public ResponseResult<MachineStatsDto> getStatistics(@RequestParam Map<String, String> filters) {
        MachineStatsDto stats = machineService.getStatistics(filters);
        return ResponseResult.success(stats);
    }

    @GetMapping("/export")
    public ResponseEntity<byte[]> exportStatistics(@RequestParam Map<String, String> filters) {
        byte[] csvData = machineService.exportStatistics(filters);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", "machine_statistics.csv");
        return ResponseEntity.ok()
                .headers(headers)
                .body(csvData);
    }

    @GetMapping("/predict")
    public ResponseResult<List<MachineDto>> predictMachineStatus() {
        List<MachineDto> predictions = machineService.predictMachineStatus();
        return ResponseResult.success(predictions);
    }

    @PostMapping("/add")
    public ResponseResult<MachineDto> addMachine(@RequestBody MachineRequest request) {
        MachineDto machine = machineService.addMachine(request);
        return ResponseResult.success(machine);
    }

    @PutMapping("/update")
    public ResponseResult<MachineDto> updateMachine(@RequestBody MachineRequest request) {
        MachineDto machine = machineService.updateMachine(request);
        return ResponseResult.success(machine);
    }

    @PostMapping("/list")
    public ResponseResult<Page<MachineDto>> getMachineList(@RequestBody Map<String, String> filters) {
        Page<MachineDto> machines = machineService.getMachineList(filters);
        return ResponseResult.success(machines);
    }

    @DeleteMapping("/delete/{id}")
    public ResponseResult<Void> deleteMachine(@PathVariable Long id) {
        machineService.deleteMachine(id);
        return ResponseResult.success(null);
    }
}